#include "func.h"
#include <cstddef>
#include <sys/socket.h>

#define MAX_EVENT_SIZE 100
#define MAX_TIMEOUT 5000


int main()
{
    //1.socket
    int listenfd = socket(AF_INET,SOCK_STREAM,0);
    if(listenfd < 0){
        perror("socket");
        return EXIT_FAILURE;
    }

    int on = 1;
    setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    
    //2.bind
    struct sockaddr_in serveraddr;
    memset(&serveraddr,0,sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(8000);
    serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int ret = bind(listenfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
    if(ret < 0){
        perror("bind");
        close(listenfd);
        return EXIT_FAILURE;
    }

    //3.listen
    ret = listen(listenfd,10); //允许同时处理10个客户连接 
    if(ret < 0){
        perror("listen");
        close(listenfd);
        return EXIT_FAILURE;
    }

    int netfd = accept(listenfd,NULL,NULL);
    while(1){
        char buf[1024] = {0};
        int ret = read(STDIN_FILENO,buf,sizeof(buf));
        ret = send(netfd, buf,strlen(buf),0); 
        printf("send %d bytes \n",ret);

        memset(buf,0,sizeof(buf));
        ret = recv(netfd,buf,sizeof(buf),0);
        printf("recv %d bytes, buf : %s \n",ret,buf);
    }
}
